package com.msg.xml;

import java.io.File;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * XMLHandler create the XML parser for the uploaded xml files
 * and find the data with given tag
 * @author jeson9603
 *
 */
public class XMLHandler {
	//a singleton of handler, for the same file
	private static XMLHandler instance;
	private String fileName;
	private DocumentBuilder docBuilder;
	private Document doc;
	private NodeList nList;
	private int currentIndex;
	private XMLHandler() {}
	
	/**
	 * given a file name, and create a XML parser for this file
	 * @param fileName : the absolute path for XML file
	 * @return
	 */
	public static XMLHandler createInstance(String fileName) {
		//if current instance is null or current instance point to other files
		//create a new instance with given new fileName
		if((null == instance) || (instance.fileName.compareTo(fileName) != 0)) {
			instance = new XMLHandler();
			try {
				File file = new File(fileName);
				DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
				instance.docBuilder = dbFactory.newDocumentBuilder();
				instance.doc = instance.docBuilder.parse(file);
				instance.doc.getDocumentElement().normalize();
				instance.nList = instance.doc.getElementsByTagName("t0");
			}
			catch(Exception ex) {
				ex.printStackTrace();
			}
		}
		return instance;
	}
	
	public static XMLHandler getInstace() {
		return instance;
	}
	
	public static void closeHandler() {
		instance = null;
	}
	
	/**
	 * get the string content of a single line in xml file given the tag.
	 * @param tag : the name of tag
	 * @return
	 */
	public String getDataByTag(String tag) {
		Node currentNode = findNodeByTag(tag);
		return currentNode.getNextSibling().getTextContent();
	}
	
	/**
	 * move the index to the tag's position with the specific tag name
	 * @param tag : the tag need of our position
	 * @return
	 */
	public Node findNodeByTag(String tag) {
		while(currentIndex < nList.getLength()) {
			Node node = nList.item(currentIndex++);
			if(node.getTextContent().compareTo(tag) == 0) {
				return node;
			}
		}
		return null;
	}
	
	public ArrayList<String> getDataListByNode(Node node) {
		ArrayList<String> result = new ArrayList<String>();
		while(node != null) {
			result.add(node.getTextContent());
			node = node.getNextSibling();
		}
		return result;
	}
	
	public ArrayList<String> getDataListByTag(String tag) {
		Node currentNode = findNodeByTag(tag);
		return getDataListByNode(currentNode);
	}
	
	public ArrayList<String> getDataList() {
		Node currentNode = nList.item(currentIndex++);
		return getDataListByNode(currentNode);
	}
	
	public void moveCursorForward() {
		currentIndex++;
	}
	
}
